/*
 * @Description: 层级列表
 * @Author: Rfan
 * @Date: 2022-01-25 18:02:15
 * @LastEditTime: 2022-06-21 18:32:34
 */

import React, { useEffect, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { TableRowSelection } from 'antd/lib/table/interface';
import { fetchArchiveProp, searchArchivesLevel } from '@/api/metadata';
import { displayTitle, showKeysList } from '@/utils/list';
import { useLevelLayoutContext } from '../contexts/LevelLayoutContext';
import { fetchDownLevelList } from '@/api/archives/archives';

const { Column } = Table;
const LevelTable = ({ data }: any) => {
  const { setLevelMatedata, setNextLevel } = useLevelLayoutContext();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [fieldList, setFieldList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [downLevel, setDownLevel] = useState<any>({});
  const [downLevelQuery, setDownLevelQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {
      archiveTypeId: 0,
      level: 0
    }
  });

  /**
   * @description: 案卷表格选中相关
   * @param {number[]} selectedKeys
   */
  const onSelectChange = (selectedKeys: number[]) => {
    setSelectKey(selectedKeys[0]);
  };

  const rowSelection: TableRowSelection<any> = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange
  };

  useEffect(() => {
    setLoading(true);
    if (data.upperInfo?.archiveTypeId) {
      const query = JSON.parse(JSON.stringify(downLevelQuery));
      query.param = data.upperInfo;
      fetchDownLevelList(query)
        .then((res: any) => {
          const { data } = res;
          if (data.results && data.results.data.length > 0) {
            setList(data.results.data);
            setFieldList(data.results.fields);
            setDownLevel(data.results.downLevel);
          } else {
            setList([]);
          }
        })
        .finally(() => {
          setLoading(false);
        });
    } else {
      searchArchivesLevel(data)
        .then((res: any) => {
          console.log('table', res.data);
          setList(res.data.data);
          setFieldList(res.data.fields);
          setDownLevel(res.data.downLevel);
        })
        .finally(() => {
          setLoading(false);
        });
    }
    fetchArchiveProp(data).then((res: any) => {
      setLevelMatedata(data.level, res.data);
    });
  }, [data.upperInfo]);

  useEffect(() => {
    setDownLevelQuery((state) => {
      const { param: _param } = state;
      if (downLevel) {
        _param.archiveTypeId = downLevel.archiveTypeId;
        _param.level = downLevel.level;
      }
      return {
        ...state,
        param: _param
      };
    });
  }, [downLevel]);

  /**
   * @description: 案卷列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    setSelectKey(record.ID);
  };

  const setSelectKey = (key: number): void => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(key) < 0) {
      setSelectedRowKeys([key]);
      setNextLevel({ ...downLevel, downLevelId: key });
    }
  };

  return (
    <div>
      <Table
        dataSource={list}
        loading={loading}
        rowKey="ID"
        rowSelection={rowSelection}
        scroll={{ x: 'max-content' }}
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
      >
        {showKeysList(list[0], fieldList).map((key) => (
          <Column title={displayTitle(key, fieldList)} dataIndex={key} key={key} align="center" />
        ))}
        {list.length > 0 && (
          <Column
            title="操作"
            key="action"
            align="center"
            fixed="right"
            render={() => {
              return (
                <Space>
                  <Button type="text" danger disabled>
                    删除
                  </Button>
                </Space>
              );
            }}
          />
        )}
      </Table>
    </div>
  );
};

export default LevelTable;
